package com.qiyadeng.wechat.roo.web;
import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.qiyadeng.wechat.roo.model.Store;

@RequestMapping("/stores")
@Controller
@RooWebScaffold(path = "stores", formBackingObject = Store.class)
public class StoreController {
	
	private Logger logger = LoggerFactory.getLogger(StoreController.class);

	
	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Store store, BindingResult bindingResult, Model uiModel, @RequestParam("storePicContent")CommonsMultipartFile storePicContent, HttpServletRequest httpServletRequest) {
//        if (bindingResult.hasErrors()) {
//            populateEditForm(uiModel, store);
//            return "stores/create";
//        }
        String path = httpServletRequest.getSession().getServletContext().getRealPath("")
        		+File.separator+"upload"+File.separator;
        //String path = httpServletRequest.getSession().getServletContext().getRealPath("")
        //		+File.pathSeparator+"upload"+File.pathSeparator+new Date().getTime()+File.pathSeparator;
        File savePathFile = new File(path);
        if(!savePathFile.exists()){
        	savePathFile.mkdirs();
        }
        File dest = new File(path + storePicContent.getOriginalFilename());//TODO 暂时用绝对路径
        
        try {
			storePicContent.transferTo(dest);
			store.setStorePic("/upload/"+storePicContent.getOriginalFilename());
			/*
			 * http://localhost:8080/WeChatDemo/resources/upload/log.txt
			 *  resources/upload/log.txt
			 */
		} catch (Exception e) {
			logger.warn("upload file exception:" + e.getMessage());
			return "stores/create";
		}
        uiModel.asMap().clear();
        store.persist();
        return "redirect:/stores/" + encodeUrlPathSegment(store.getId().toString(), httpServletRequest);
    }
}
